package com.igeek.boot.config;

import com.igeek.boot.entity.Pet;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.util.UrlPathHelper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author fengqq
 * @Description TODO
 * @Date 2024/8/15  15:43
 */
@Configuration
public class WebMVCConfig  {
    @Bean
    public WebMvcConfigurer webMvcConfigurer(){
        return new WebMvcConfigurer() {
            //配置路径解析规则
            @Override
            public void configurePathMatch(PathMatchConfigurer configurer) {
                UrlPathHelper urlPathHelper = new UrlPathHelper();
                //设置 不移除 url请求路径中的分号
                urlPathHelper.setRemoveSemicolonContent(false);
                configurer.setUrlPathHelper(urlPathHelper);
            }

            //添加自定义转换器
            @Override
            public void addFormatters(FormatterRegistry registry) {
                //自定义的时间转换器 ==》 @DateTimeFormat
                Converter customDateConverter = new Converter<String, Date>() {
                    @Override
                    public Date convert(String source) {
                        if(StringUtils.hasLength(source)) {
                            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                            Date date = null;
                            try {
                                date = dateFormat.parse(source);
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                            return date;
                        }
                        return null;
                    }
                };
                //registry.addConverter(customDateConverter); 生效自定义的转换器
                //生效自定义的转换器 String-->Pet
                registry.addConverter(customStringPetConverter());
            }
        };
    }

    //配置自定义转换器String-->Pet
    @Bean
    public Converter<String,Pet>  customStringPetConverter(){
        Converter<String, Pet> stringPetConverter = new Converter<>() {
            @Override
            public Pet convert(String source) {
                if(StringUtils.hasLength(source)) {
                    String[] arr = source.split("&");
                    return new Pet(arr[0],Integer.parseInt(arr[1]));
                }
                return null;
            }
        };
        return stringPetConverter;
    }


}
